package com.yupi.yupicturebackend.manager;


import cn.hutool.core.io.FileUtil;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.exception.CosServiceException;
import com.qcloud.cos.model.COSObject;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.PicOperations;
import com.yupi.yupicturebackend.config.CosClientConfig;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

@Component
public class CosManager {

    @Resource
    private CosClientConfig  cosClientConfig;
    @Resource
    private COSClient cosClient;

    // 将本地文件上传到 COS
    public PutObjectResult putObject( String key, File file) throws CosClientException, CosServiceException{
        PutObjectRequest putObjectRequest = new PutObjectRequest(cosClientConfig.getBucketName(), key, file);
        return cosClient.putObject(putObjectRequest);

    }
    //下载文件到本地
    public COSObject getObject(String key) throws CosClientException, CosServiceException{
        return cosClient.getObject(cosClientConfig.getBucketName(), key);
    }

    //上传对象（附带图片信息）
    public PutObjectResult putPictureObject(String key,File file){
        PutObjectRequest putObjectRequest = new PutObjectRequest(cosClientConfig.getBucketName(), key, file);

        //对图片进行处理
        PicOperations picOperations = new PicOperations();
        //1表示返回原图信息
        picOperations.setIsPicInfo(1);
        //图片压缩
        List<PicOperations.Rule> rules=new ArrayList<>();
        String webpKey= FileUtil.mainName(key)+".webp";
        PicOperations.Rule compressRule=new PicOperations.Rule();
        compressRule.setRule("imageMogr2/format/webp");
        compressRule.setBucket(cosClientConfig.getBucketName());
        compressRule.setFileId(webpKey);
        rules.add(compressRule);
        if(file.length()>2*1024){
            //缩略图处理
            PicOperations.Rule thumbnailRule= new PicOperations.Rule();
            thumbnailRule.setBucket(cosClientConfig.getBucketName());
            String thumbnailKey= FileUtil.mainName(key)+"_thumbnail."+FileUtil.getSuffix(key);
            thumbnailRule.setFileId(thumbnailKey);
            //缩放规则
            thumbnailRule.setRule(String.format("imageMogr2/thumbnail/%sx%s>",128,128));
            rules.add(thumbnailRule);
        }

        picOperations.setRules(rules);
        putObjectRequest.setPicOperations(picOperations);
        return cosClient.putObject(putObjectRequest);
    }
    //删除对象
    public void deleteObject(String key){
        cosClient.deleteObject(cosClientConfig.getBucketName(), key);
    }
}
